from django.db import migrations


def allow_legacy_columns_nullable(apps, schema_editor):
    connection = schema_editor.connection
    table = "deal_bid_opening_record"
    with connection.cursor() as cursor:
        try:
            cursor.execute(f"SHOW COLUMNS FROM `{table}`")
            columns = cursor.fetchall()
        except Exception:
            columns = []

    allowed = {
        "id",
        "opening_time",
        "opening_location",
        "project_id",
        "crawl_task_id",
        "created_at",
        "updated_at",
    }

    for field, dtype, null_flag, _key, default_val, _extra in columns:
        if field in allowed:
            continue
        ddl = f"ALTER TABLE `{table}` MODIFY COLUMN `{field}` {dtype} NULL DEFAULT NULL"
        with connection.cursor() as cursor:
            cursor.execute(ddl)


def noop_reverse(apps, schema_editor):
    pass


class Migration(migrations.Migration):
    dependencies = [
        ('deal', '0006_fix_transaction_legacy_columns'),
    ]

    operations = [
        migrations.RunPython(allow_legacy_columns_nullable, noop_reverse),
    ]